const axios = require('axios')
const fs = require('fs')
const path = require('path')
const md5 = require('md5')
const { Model, Database } = require('mongorito')
const gm = require('gm')
const tesseract = require('node-tesseract')

async function tryPraseCode(path) {
  return new Promise((resolve, reject) => {
    tesseract.process(path, { psm: 6 }, function(err, text) {
      if (err) {
        reject(err)
      } else {
        resolve(text)
      }
    })
  })
}

async function sleep(timeout = 3000) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(true)
    }, timeout)
  })
}
async function run(params) {
  let index = 0
  do {
    const { data: codeUrl } = await axios({ url: 'http://www.aihuishou.com/util/GetImageCaptcha.html' })
    if (codeUrl.data) {
      const { data: buffer } = await axios({ url: codeUrl.data, responseType: 'arraybuffer' })
      const fileName = md5(buffer)
      if (fs.existsSync(`./CodeImages/${fileName}.jpeg`)) {
        console.log('exists', fileName)
      } else {
        fs.writeFileSync(`./CodeImages/${fileName}.jpeg`, buffer)
      }
    }
    console.log('index', index)
    index++
  } while (index <= 10000)
}

class CodeImage extends Model {}

async function splitCode(file, newFile, rect) {
  return new Promise(async (resolve, reject) => {
    gm(file)
      .threshold(55, true)
      // .channel('Gray')
      // .monochrome()
      // .despeckle()
      // .antialias()
      //   .crop(190, 70, 10, 0)
      //   .crop(...rect)
      .write(newFile, err => {
        if (err) console.log(err)
      })
    const result = (await tryPraseCode(newFile)).trim()
    resolve(result)
  })
}

function tryParseNumber(params) {
  try {
    let result = parseInt(params)
    if (result) {
      return params
    } else {
      return null
    }
  } catch (error) {
    return null
  }
}

async function checkCode(params) {
  fs.readdir('./CodeImages/', async (err, files) => {
    if (err) console.log(err)
    else {
      for (let index = 0; index < files.length; index++) {
        const file = files[index]
        let result = ''
        result = await splitCode('./CodeImages/' + file, './caches/' + 'dsdsda' + '.jpeg')
        console.log('测试结果', './CodeImages/' + file, '   ', result)
        await sleep(3000)
      }
    }
  })
}

// checkCode()

exports.parseYZM = async function(path) {
  return new Promise(async (resolve, reject) => {
    let result = ''
    result = await splitCode('./caches/yzm.jpeg', './caches/test_yzm.jpeg')
    // result = tryParseNumber(result)

    console.log('parseYZM', result)
    if (/\d{4}/.test(result)) {
      resolve(result)
    } else {
      resolve(null)
    }
  })
}
